﻿namespace Webapi.Middlewares
{
    /// <summary>
    /// 权限控制中间件
    /// </summary>
    public class ApiPermissionMiddleware
    {
        private readonly RequestDelegate _next;

        public ApiPermissionMiddleware(RequestDelegate next)
        {
            _next = next ?? throw new ArgumentNullException(nameof(next));
        }

        public async Task Invoke(HttpContext context)
        {
            // 修复：确保 GetEndpoint 扩展方法可用
            var endpoint = context.GetEndpoint();

            if (endpoint != null)
            {
                // EndpointRoutingMiddleware uses this flag to check if the Authorization middleware processed auth metadata on the endpoint.
                // The Authorization middleware can only make this claim if it observes an actual endpoint.
                //context.Items[AuthorizationMiddlewareInvokedWithEndpointKey] = AuthorizationMiddlewareWithEndpointInvokedValue;
            }

            // 通过终结点路由元素IAuthorizeData来获得对于的AuthorizeAttribute并关联到AuthorizeFilter中
            //var authorizeData = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>() ?? Array.Empty<IAuthorizeData>();
            //var policy = await AuthorizationPolicy.CombineAsync(_policyProvider, authorizeData);
            //if (policy == null)
            //{
            //    await _next(context);
            //    return;
            //}

            var per = endpoint?.Metadata.FirstOrDefault(item => item.GetType().Name == "ApiPermissionsAttribute");
            if (per != null)
            {
                var permissionName = per.GetType().GetProperty("Permission")?.GetValue(per)?.ToString();
                var user = context.User;
                // 这里可以添加更多的权限检查逻辑
                // 例如，检查用户的角色或声明中是否包含所需的权限
                // 如果权限检查失败，返回403 Forbidden
                bool hasPermission = false; // 替换为实际的权限检查逻辑
                var Permissionlist = user.Claims.FirstOrDefault(item => item.Type == "Permission");
                if (Permissionlist != null && permissionName != null)
                {
                    var permissions = Permissionlist.Value.Split(',');
                    if (permissions.Contains(permissionName))
                    {
                        hasPermission = true;
                    }
                }

                if (!hasPermission)
                {
                    context.Response.StatusCode = StatusCodes.Status403Forbidden;
                    await context.Response.WriteAsync("Forbidden");
                    return;
                }
            }
            await _next(context);
        }
    }
}
